package com.bgs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bgs.pojo.*;
import com.bgs.pojo.vo.GandStu;
import com.bgs.pojo.vo.GradeGrade;
import com.bgs.pojo.vo.GradeVo;
import com.bgs.pojo.vo.studentGradeRelationVo;
import com.bgs.service.GradeService;
import com.bgs.utils.MyContent;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Auther: 梁玉杰
 * @Date: 2021/8/10 11:30
 * @Description: TODO
 */
@RestController
@RequestMapping("/gradeVue")
@CrossOrigin
public class GradeVueController {

    Logger log = LogManager.getLogger();

    @Autowired
    private GradeService gradeService;

    @RequestMapping("/findAllGrade")
    public R findAllGrade(@RequestBody(required = false) GradeVo grade){

        log.info("模糊查询的"+grade);

        Map<String,Object> m = new HashMap<>();
        //设置分页信息(当前页码，每页显示数量)
        PageHelper.startPage(grade.getPage(),grade.getLimit());
        //调用service查询班级方法
        List<Grade> l = gradeService.findAll(grade);

        //把全查回来的班级集合，每个的班级名称再拿出来查询当前班级的现有学生
        for (int i = 0; i < l.size(); i++) {

            log.info("总数"+l.size());
            log.info(l.get(i).getGradeId());
            //当前宿舍的现住学生
            Integer number = gradeService.number(l.get(i).getGradeId());

            l.get(i).setGraStuNumber(number+"(已有)/"+l.get(i).getStudentsNumber()+"(总数)");

        }

//        for (Dormitory dor : d) {
//           log.info(dor.getDormitoryName());
//            //当前宿舍的现住学生
//            Integer number = dormitoryService.number(dor.getDormitoryName());
//
//            dor.setDorstuNumber(number+"(已用)/"+dor.getBedNumber()+"总数");
//
//        }


        //创建分页对象
        PageInfo<Grade> pageInfo = new PageInfo<>(l);
        log.info("PageInfo<Grade>"+pageInfo);

        return  R.ok().data("total",pageInfo.getTotal()).data("rows",pageInfo.getList());

    }

    //添加班级
    @PostMapping("/addc")
    public R addc(@RequestBody GradeGrade gs){

        log.info("添加的"+gs);
        Grade g = new Grade();
        g.setGradeName(gs.gg.getGradeName());
        g.setClassTeacherId(gs.gg.getClassTeacherId());
        g.setClassroomClassroomId(gs.gg.getClassroomClassroomId());
        g.setLecturerId(gs.gg.getLecturerId());
        g.setStudentsNumber(gs.gg.getStudentsNumber());
        g.setClassTeacherName(gs.getClassTeacherName());
        g.setLecturerName(gs.getLecturerName());

        boolean flag = (gradeService.insertSelective(g) > 0);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    //修改班级
    @PostMapping("/updc")
    public R updc(@RequestBody GradeGrade gs){
        Map<String,Object> m = new HashMap<>();
        log.info("修改的VO"+gs);
        Grade g = new Grade();

        g.setGradeName(gs.gg.getGradeName());
        g.setClassTeacherId(gs.gg.getClassTeacherId());
        g.setClassroomClassroomId(gs.gg.getClassroomClassroomId());
        g.setLecturerId(gs.gg.getLecturerId());
        g.setStudentsNumber(gs.gg.getStudentsNumber());
        g.setClassTeacherName(gs.getClassTeacherName());
        g.setLecturerName(gs.getLecturerName());
        g.setPkId(gs.gg.getPkId());


        boolean flag = (gradeService.updateByPrimaryKeySelective(g) > 0);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @GetMapping("/getc/{id}")
    public R getTeacher(@PathVariable String id){
        Grade g = gradeService.selectByPrimaryKey(Integer.valueOf(id));
        return R.ok().data("teacher",g);
    }

    /**
     * 删除班级
     */
    @RequestMapping("/deleteById/{stuId}")
    public R cdeleteBypkId(@PathVariable String stuId){
        boolean flag =(gradeService.deleteById(Integer.valueOf(stuId))>0);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    /**
     * 批量删除班级
     */
    @RequestMapping("/batchDeletelist/{ids}")
    public R cbatchDelete(@PathVariable Integer[] ids){
        System.out.println("前端传入的数组：："+ids);
        int count = 0;
        for (int i = 0; i < ids.length; i++) {
//            System.out.println("前端传入的数组：："+ids[i]);
            int a = gradeService.deleteById(ids[i]);
            if(a>0){
                count++;
            }
        }
        //判断受影响行数是否为0
        if (count>0){
            return R.ok();
        }else {
            return R.error();
        }
    }


    //详情功能的班级添加学生信息
    @RequestMapping("/SGRaddStu")
    public R SGRaddStu(@RequestBody GandStu g){

        System.out.println("添加学生的"+g);
//        System.out.println("添加学生的"+s);
//        System.out.println(stu);
        studentGradeRelation sg = new studentGradeRelation();
        sg.setStudentId(g.stu.getStuId().toString());  //学生的Id
        sg.setGradeGradeId(g.cinfor.getGradeId());  //班级的ID
        sg.setGradeGradeName(g.cinfor.getGradeName());  //班级名称

        boolean flag = (gradeService.insertGS(sg) > 0);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }


    //详情功能的班级批量添加学生信息
    @RequestMapping("/SGRbatchaddStu")
    @ResponseBody
    public Map<String,Object> SGRbatchaddStu(@RequestBody String s){

        JSONObject jsonObject = JSONObject.parseObject(s);
        String gradeId = jsonObject.getString("gradeId");       //班级ID
        String gradeName = jsonObject.getString("gradeName");   //班级名称
        JSONArray arrId = jsonObject.getJSONArray("stuId");     //要添加的学生数组

        studentGradeRelation sg = new studentGradeRelation();
        sg.setGradeGradeId(gradeId);  //班级的ID
        sg.setGradeGradeName(gradeName);  //班级名称
        int count = 0;
        for (int i = 0; i < arrId.size(); i++) {
            sg.setStudentId(arrId.getInteger(i).toString());  //学生的Id
            if (gradeService.insertGS(sg) > 0){
                count++;
            }
        }
        HashMap<String, Object> m = new HashMap<>();

        if(count>0){
            m.put("success",true);
            m.put("message","添加成功");
        }else{
            m.put("success",false);
            m.put("message","添加失败");
        }

        return m;
    }


    //详情功能的展示本班学生信息的
    @RequestMapping("/gsfindAllgs")
    public R gsfindAllgs(@RequestBody(required = false) studentGradeRelationVo sg){

        log.info("模糊查询的"+sg);

        //设置分页信息(当前页码，每页显示数量)
        PageHelper.startPage(sg.getPage(),sg.getLimit());
        Grade g = new Grade();
        //调用service查询班级方法
        List<studentGradeRelation> l = gradeService.gsfindAllgs(sg);

        //创建分页对象
        PageInfo<studentGradeRelation> gradePageInfo = new PageInfo<>(l);
        log.info("PageInfo<studentGradeRelation>"+gradePageInfo);

        return  R.ok().data("total",gradePageInfo.getTotal()).data("rows",gradePageInfo.getList());

    }

    /*
    删除本班学生
     */
    @RequestMapping("/deleteByIdSstu/{stuId}")
    public R deleteByIdSstu(@PathVariable Integer pkId){

        boolean flag =(gradeService.deleteByIdSstu(pkId)>0);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }


    /**
     * 批量删除本班的学生
     */
    @RequestMapping("/deleteBySstuID")
    @ResponseBody
    public Map<String, Object> deleteBySstuID(@RequestBody String ids){
        System.out.println(ids);
        Map<String,Object> map = new HashMap<>();
        int count = 0;
        JSONObject jsonObject = JSONObject.parseObject(ids);
        JSONArray arrId = jsonObject.getJSONArray("ids");

//        JSONArray arrId = JSONArray.parseArray(ids);

        log.info("arrId::: " + arrId);
        for (int i = 0; i < arrId.size(); i++) {
            log.info("批量删除"+arrId.getInteger(i));
            count = gradeService.deleteByIdSstu(arrId.getInteger(i));
            if(count>0){
                map.put("success",true);
                map.put("message","删除成功");
            }
        }
        //判断受影响行数是否为0
        if(count<=0){
            map.put("success",false);
            map.put("message","删除失败");
        }
        return map;
    }

    //班级班主任的下拉框
    @GetMapping("/GradexlkBZR")
    public R GradexlkBZR(){

        List<EmployeeInfo> glist = gradeService.GradexlkBZR();
        log.info("GGGGG"+glist);
        return R.ok().data("items",glist);
    }

    //班级讲师的下拉框
    @GetMapping("/GradexlkJS")
    public R GradexlkJS(){

        List<EmployeeInfo> glist = gradeService.GradexlkJS();
        log.info("GGGGG"+glist);
        return R.ok().data("items",glist);
    }



}
